﻿using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.BaseLibrary;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Core.Toolkit.Core.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application
{
    [AutoDi()]
    public class JG_DutiesTemplateService : BaseAppService<JG_DutiesTemplateDto, JG_DutiesTemplate, JG_DutiesTemplateRepository>
    {
        readonly TempDirDiHelp _TempDirHelp;
        readonly ExcelHelp _excelHelp;
        CoreDBContext _dbContext;
        readonly UserIdentity _userIdentity;
        
        public JG_DutiesTemplateService(JG_DutiesTemplateRepository repository, ExcelHelp excelHelp,TempDirDiHelp tempDirHelp) : base(repository)
        {
            _excelHelp = excelHelp;
            _TempDirHelp = tempDirHelp;
        }



        private LoadPageOffsetModelAuto<JG_DutiesTemplate, JG_DutiesTemplateDto>
            GetLoadPageOffsetMode(PagingModel<JG_DutiesTemplateDto>
                pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking();
            loadPageOffsetModel.QueryWhere = this.CreateQRList()

     .Add("AssessmentID", "=") //
     .Add("AssessmentContent", "=") //
     .Add("AssessmentMainPoints", "=") //
     .Add("VoluationNumber", "=") //
     .Add("CreateFactory", "=") //
     .Add("CreateDept", "=") //
     .Add("UpdateDept", "=");//


            loadPageOffsetModel.BasqQuery = baseQuery;
            loadPageOffsetModel.Order = orderModel => orderModel.CreateTime;
            loadPageOffsetModel.Selector = model => new JG_DutiesTemplate()
            {
                Id = model.Id,
                AssessmentID = model.AssessmentID,//
                AssessmentContent = model.AssessmentContent,//
                AssessmentMainPoints = model.AssessmentMainPoints,//
                VoluationNumber = model.VoluationNumber,//
                CreateFactory = model.CreateFactory,//
                CreateDept = model.CreateDept,//
                UpdateDept = model.UpdateDept,//
            };
            return loadPageOffsetModel;
        }


        public async Task<IPageModel<JG_DutiesTemplateDto>> GetList(PagingModel<JG_DutiesTemplateDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }


        public async Task<string>
            Export(PagingModel<JG_DutiesTemplateDto>
                pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select(model => new
            {
                model.AssessmentID,
                AssessmentID_title = "",
                model.AssessmentContent,
                AssessmentContent_title = "",
                model.AssessmentMainPoints,
                AssessmentMainPoints_title = "",
                model.VoluationNumber,
                VoluationNumber_title = "",
                model.CreateFactory,
                CreateFactory_title = "",
                model.CreateDept,
                CreateDept_title = "",
                model.UpdateDept,
                UpdateDept_title = "",
            }).ToList();




            return _excelHelp.Create(excelData);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        //public async Task<List<string>> ImportAsync(IFormFile file, string data)
        public async Task<List<string>> ImportAsync(IFormFile file)
        {
            var extension = System.IO.Path.GetExtension(file.FileName);
            var filePath = _TempDirHelp.GetFilePath(extension);
            await Filehelp.WriteFileAsync(file.OpenReadStream(), filePath);

            var dataList = new List<JG_DutiesTemplate>();
            var errMsgList = new List<string>();

            IWorkbook workbook = new XSSFWorkbook(filePath);
            try
            {
                var sheet = workbook.GetSheetAt(0);
                int rowCount = sheet.LastRowNum;

                //验证模板是否正确
                var first = sheet.GetRow(0);
                if (first.GetCell(0)?.ToString() != "评估内容" ||
                    first.GetCell(1)?.ToString() != "评估要点参考" ||
                     first.GetCell(2)?.ToString() != "赋值分数"
                    )
                {
                    errMsgList.Add($"请确认模板是否正确!");
                }
                for (int i = 1; i <= rowCount; i++)
                {
                    var row = sheet.GetRow(i);
                    var entity = new JG_DutiesTemplate();
                    entity.AssessmentContent = row.GetCell(0)?.ToString();
                    entity.AssessmentMainPoints = row.GetCell(1)?.ToString();
                    if (!string.IsNullOrWhiteSpace(row.GetCell(2)?.ToString()))
                    {
                        if (!IsInteger(row.GetCell(2)?.ToString()))
                        {
                            errMsgList.Add($"第{i}行，【赋值分数】列 必须为正整数");
                        }
                    }
                    entity.VoluationNumber = Convert.ToInt32(row.GetCell(2)?.ToString());
                    dataList.Add(entity);
                }
            }
            catch (Exception ex)
            {
                errMsgList.Add($"导入异常:" + ex.Message);
            }
            finally
            {
                workbook.Close();
            }
            if (errMsgList.Any())
                return errMsgList;
            await _repository.Set.AddRangeAsync(dataList);
            await _repository.SaveAsync();
            System.IO.File.Delete(filePath);
            return errMsgList;
        }

        protected bool IsInteger(string value)
        {
            string pattern = @"^[0-9]*[1-9][0-9]*$";
            return Regex.IsMatch(value, pattern);
        }


    }

}
